package at.codebase.web.util.i18n;

import java.util.HashMap;
import java.util.logging.Logger;

import at.codebase.core.Settings;

/**
 * This class is used to load and cache I18N instances of different language
 * files. Call the static method i18n(locale) to get an instance of the specific
 * language.
 * 
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 * 
 */
public class I18NFactory {

	private static final Logger log = Logger.getLogger(I18NFactory.class
			.getName());

	private static HashMap<String, I18N> languageInstances = new HashMap<String, I18N>();

	private static final I18N defaultLang;

	static {
		defaultLang = new I18N(I18N.DEFAULT_LANGUAGE);
		try {
			defaultLang.load();
		} catch (I18NFileLoadingException e) {
			log.severe(e.getMessage());
		}
	}

	/**
	 * Returns a I18N object of the given language. This method should be used
	 * for every localization request because it caches the file content instead
	 * of reloading it every time.
	 * 
	 * @param locale
	 * @return an I18N object for the given language
	 */
	public static I18N i18n(I18NLocale locale) {

		if (!Settings.I18N_FILE_CACHING) {
			I18N instance = new I18N(locale);
			try {
				instance.load();
			} catch (I18NFileLoadingException e) {
				log.severe("I18N Cache is not enabled and i18n["
						+ locale.getLocale() + "] file is corrupt");
			}
			return instance;
		}

		I18N instance = languageInstances.get(locale.getLocale());
		if (instance != null)
			return instance;

		try {
			return cachedLoad(locale);
		} catch (I18NFileLoadingException e) {
			log.severe(e.getMessage());
			return defaultLang;
		}
	}

	public static I18N cachedLoad(I18NLocale locale)
			throws I18NFileLoadingException {
		I18N instance = new I18N(locale);
		instance.load();
		languageInstances.put(locale.getLocale(), instance);
		return instance;
	}

	public static class I18NFileLoadingException extends Exception {

		public I18NFileLoadingException(String message) {
			super(message);
		}

	}
}
